<?php
require_once ("views/searchView.php");

class SearchController {
    private $m_searchViewer;
    private $m_searchModel;

    /**
     * @param SearchModel $searchModel
     */
    public function __construct(SearchModel $a_searchModel) {
        $this -> m_searchModel = $a_searchModel;
        $this -> m_searchViewer = new searchView();
    }

    public function doControll() {
        
        $searchTypes = array() ;
        $returnString = '' ;

        if ($handle = opendir('searchInterfaces/')) {
    
            /* This is the correct way to loop over the directory. */
            while (false !== ($file = readdir($handle))) {
                $fileType = preg_split("/\./", $file) ;
                if($fileType[1] == 'php') {
                    
                    require_once('searchInterfaces/'.$file) ;
                    $searchTypes[] = $fileType[0] ;
                }

            }

            closedir($handle);
        } 
        
        if($this->m_searchViewer->getSearchType() !== NULL) {
            $class = $this->m_searchViewer->getSearchType() ; 
            $oClass = new ReflectionClass($class);
            $params = $oClass->getConstants() ;    
        }

        $returnString .= $this->m_searchViewer->searchTypes($searchTypes) ;
        
        if(isset($params)) {
            $returnString .= $this->m_searchViewer->searchBox($params) ;
        }
        
        if($this->m_searchViewer->doneSearch()) {
            $searchClass = $this->m_searchViewer->getSearchType() ;
            $result = $this->m_searchModel->search(new $searchClass($this->m_searchViewer->getSearchValue(), $this->m_searchViewer->getSearchParam())) ;
            $returnString .= $this->m_searchViewer->showResults($result) ;
        }
        
        return $returnString ;
        
        
    } 
   
}